package tech.yunland.shop.web;

import com.alibaba.fastjson.JSON;
import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.common.PinYinUtil;
import com.moyuer.bsf.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import tech.yunland.shop.domain.dao.GoodsDao;
import tech.yunland.shop.domain.model.Goods;
import tech.yunland.shop.domain.model.TagGoods;
import tech.yunland.shop.domain.service.GoodsService;

import javax.validation.Valid;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品信息控制器
 * 
 * @author: 袁首京<yuanshoujing@gmail.com>
 */
@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController {

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private GoodsDao goodsDao;

	/**
	 * 保存商品
	 * 
	 * @param goods
	 * @return
	 */
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public void saveOrUpdate(@RequestBody @Valid Goods goods) {
		logger.info(JSON.toJSONString(goods, true));

		if (goods.getOrgan() == null) {
			goods.setOrgan(primaryOrgan);
		}

		if (goods.getPrice() == null) {
			throw new RuntimeException("商品销售单价不存在");
		}

		// 分录对象赋值
		if (goods.getTagGoods() != null) {
			for (TagGoods tagGoods : goods.getTagGoods()) {
				tagGoods.setGoods(goods);
			}
		}

		goods.setSpell(PinYinUtil.getFirstSpell(goods.getName()));

		goodsService.saveOrUpdate(goods);

		saveLog("商品:[" + goods.getName() + "]保存成功！");
	}

	/**
	 * 根据主键获取商品
	 * 
	 * @param id
	 * @Return Goods
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Goods get(@PathVariable String id) {
		// 先更新使用频率
		if (!Goods.JF_ID.equals(id) && !Goods.DJQ_ID.equals(id)) {
			goodsService.updateRate(id);
		}

		Goods result = goodsService.get(id);

		return result;
	}

	/**
	 * 根据主键删除商品
	 * 
	 * @param id
	 * @Return Goods
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public void delete(@PathVariable String id) {
		Goods goods = goodsService.get(id);
		goodsService.delete(id);

		saveLog("商品:[" + goods.getName() + "]删除成功！");
	}

	/**
	 * 查询未上架和已上架的商品, 不包含内置商品
	 * 
	 * @param param
	 *            参数
	 * @param tags
	 *            标签集
	 * @param states
	 *            状态集
	 * @param page
	 *            起始索引
	 * @param rows
	 *            每页数量
	 * @return
	 * @Return List<Goods>
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public Pagination<Goods> getResultInfos(
			@RequestParam(required = false) String param,
			@RequestParam(required = false) List<String> tags,
			@RequestParam(required = false) List<Integer> states,
			@RequestParam(required = false) Integer page,
			@RequestParam(required = false) Integer rows) {

		Pagination<Goods> result = new Pagination<Goods>(page, rows);
		int startIdx = result.getStartIdx();

		int count = goodsService.getResultSize(param, states, tags, organIds,true, null);
		List<Goods> records = goodsService.getResultInfos(param, states, tags,startIdx, rows, organIds, true, null);

		result.setCount(count);
		result.setRecords(records);

		return result;
	}

	/**
	 * 查询已上架的商品, 供选择商品用, 包含内置商品
	 * 
	 * @param param
	 *            参数
	 * @param tags
	 *            标签集
	 * @param page
	 *            起始索引
	 * @param rows
	 *            每页数量
	 * @return
	 * @Return List<Goods>
	 */
	@RequestMapping(value = "/on-shelf", method = RequestMethod.GET)
	public Pagination<Goods> getOnShelfGoods(
			@RequestParam(required = false) String param,
			@RequestParam(required = false) List<String> tags,
			@RequestParam(required = false) List<Integer> kindCodes,
			@RequestParam(required = false) Integer page,
			@RequestParam(required = false) Integer rows) {

		List<Integer> states = new ArrayList<Integer>();
		states.add(1); // 上架状态

		Pagination<Goods> result = new Pagination<Goods>(page, rows);
		int startIdx = result.getStartIdx();

		int count = goodsService.getResultSize(param, states, tags, organIds,true,kindCodes);
		List<Goods> records = goodsService.getResultInfos(param, states, tags, startIdx, rows, organIds, true,kindCodes);
		
        //创建新对象存储memberPrize
		List<Goods> newRecords = new ArrayList<Goods>();

		for (Goods goods : records) {
			BigDecimal memberPrize = BigDecimal.ZERO;
			
			if (goodsDao.getMemberPrize(primaryOrganId, goods.getId()).size()<=0) {
				memberPrize = goods.getPrice();
			} else if(goodsDao.getMemberPrize(primaryOrganId, goods.getId()).size()>0) {
				memberPrize = new BigDecimal(goodsDao.getMemberPrize(primaryOrganId, goods.getId()).get(0).get("member_prize").toString());
			}
			
			goods.setMemberPrize(memberPrize);
			newRecords.add(goods);
			
		}

		result.setCount(count);
		result.setRecords(newRecords);

		return result;
	}

	/**
	 * 查询标签
	 * 
	 * @param goodsId
	 * @param tagId
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping(value = "/tag_goods/", method = RequestMethod.GET)
	public Pagination<TagGoods> getResultInfosTG(
			@RequestParam(required = false) String goodsId,
			@RequestParam(required = false) String tagId,
			@RequestParam(required = false) Integer page,
			@RequestParam(required = false) Integer rows) {

		Pagination<TagGoods> result = new Pagination<TagGoods>(page, rows);
		int startIdx = result.getStartIdx();

		int count = goodsService.getResultSizeTG(goodsId, tagId);
		List<TagGoods> records = goodsService.getResultInfoTG(goodsId, tagId,
				startIdx, rows);

		result.setCount(count);
		result.setRecords(records);

		return result;
	}

}
